﻿
using Assets.Scripts.Interface;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
/// <summary>
/// 钥匙道具
/// 1.主角拾取，为功能道具。发送字符串信息，主要和门等通信，发送密码
/// 2.订阅主角碰撞事件来获取门
/// </summary>
public class Key :AProp,Sender<string> {
    private TMessage<string> tkeyWord;
    [SerializeField, Tooltip("开门的密码")]
    private string keyWord = "test1";//用于给控制面板修改

    public override void Click()
    {
      //  info = "量子魔方:它可以解开世界上一切的秘密";
        Introduce();
    }
    
    public override void FixedAwake()
    {
        Type = PropType.FUNCTION;//类型为功能.
        tkeyWord=new TMessage<string>(keyWord,this);//初始化TMessage
     
    }

    /// <summary>
    /// 被主角拾取的逻辑
    /// </summary>
    /// <param name="other"></param>
    protected override void OnTriggerEnter(Collider other)
    {
        base.OnTriggerEnter(other);
        GameManager.Instance.Player.collisionEnter += OpenDoor;//订阅主角的碰撞事件
    }

    /// <summary>
    /// 重写道具减少函数。
    /// </summary>
    /// <param name="reduce"></param>
    public override void ReduceCount(int reduce)
    {
        base.ReduceCount(reduce);
        if (useCount==0)
        {
            GameManager.Instance.Player.collisionEnter -= OpenDoor;//使用完了则取消订阅主角的碰撞事件
        }
    }

    public TMessage<string> Send()
    {

        StartCoroutine(Wait());
        return tkeyWord;
    }

    private IEnumerator Wait()
    {
        yield return new WaitForSeconds(0.1f);
        ReduceCount(1);//钥匙有使用次数
    }


    /// <summary>
    /// 开门方法
    /// </summary>
    /// <param name="cs"></param>
    private void OpenDoor(Collision cs)
    {
        if (cs.collider.tag=="TriggerObj")
        {
           // print("ok");
            Receiver<string> door = cs.collider.GetComponent<Receiver<string>>();
            //如果是门脚本，且不需要密码，则消耗钥匙
            Gate gate = cs.collider.GetComponent<Gate>();
            if (gate != null) if (!gate.NeedWord) return;
            if (door!=null)//如果是接受字符串的receiver
            {
                tkeyWord.Reiver = door;//赋值接受者。进行通信
            }
        }
    }
    private void OnDestroy()
    {
        if (GameManager.Instance == null) return;
        if(GameManager.Instance.Player!=null)
        GameManager.Instance.Player.collisionEnter -= OpenDoor;
    }
}
